package com.payment.ktb.Fragment;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.ServiceH5WithTitleActivity;
import com.payment.ktb.activity.ShowH5Activity;
import com.payment.ktb.activity.ShowH5WithTitleActivity;
import com.payment.ktb.activity.main3.OrderDetailActivity;
import com.payment.ktb.adapter.Main1BannerPagerAdapter;
import com.payment.ktb.adapter.Main3BannerPagerAdapter;
import com.payment.ktb.adapter.PaymentOrderRecordAdapter;
import com.payment.ktb.adapter.ServiceAdapter;
import com.payment.ktb.adapter.SettleOrderRecordAdapter;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.AdvertisementEntity;
import com.payment.ktb.model.PaymentOrder;
import com.payment.ktb.model.ServiceItemEntity;
import com.payment.ktb.model.SettleOrder;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by syd on 2016/6/2.
 */
public class Fragment_main3 extends BaseFragment implements View.OnClickListener,ViewPager.OnPageChangeListener{

    ScheduledExecutorService mScheduledExecutorService = null;
    int currentItem = 0;
    ViewPager vp_main3_banner;
    LinearLayout ll_main3_banner;
    Main3BannerPagerAdapter bannerPagerAdapter = null;
    List<AdvertisementEntity> bannersList = new ArrayList<AdvertisementEntity>();
    String timestamp = String.valueOf(new Date().getTime());
    ListView lv_service;
    List<ServiceItemEntity> listDatas;
    ServiceAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main3,container,false);

        //服务条目
        lv_service = (ListView) view.findViewById(R.id.lv_service);
        lv_service.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!TextUtils.isEmpty(listDatas.get(i).getUrl())) {
                    Intent intent = new Intent(mContext, ServiceH5WithTitleActivity.class);
                    intent.putExtra("url",listDatas.get(i).getUrl());
                    startActivity(intent);
                }

            }
        });

        getServiceInfoList();


        ll_main3_banner = (LinearLayout) view.findViewById(R.id.ll_main3_banner);
        vp_main3_banner = (ViewPager) view.findViewById(R.id.vp_main3_banner);
        vp_main3_banner.addOnPageChangeListener(this);

        getBannerInfo();


        return view;
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

        }
    }


    @Override
    public void onStart() {

        super.onStart();
        //用一个定时器  来完成图片切换
        //Timer 与 ScheduledExecutorService 实现定时器的效果
        mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //通过定时器 来完成 每2秒钟切换一个图片
        //经过指定的时间后，执行所指定的任务
        //scheduleAtFixedRate(command, initialDelay, period, unit)
        //command 所要执行的任务
        //initialDelay 第一次启动时 延迟启动时间
        //period  每间隔多次时间来重新启动任务
        //unit 时间单位
        mScheduledExecutorService.scheduleAtFixedRate(new ViewPagerTask(), 5, 5, TimeUnit.SECONDS);


    }


    @Override
    public void onStop() {
        super.onStop();
        //停止图片切换
        if (mScheduledExecutorService != null) {
            mScheduledExecutorService.shutdown();
        }
    }

    public void getServiceInfoList() {


        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",timestamp);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.ServiceInfoList, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    //data
                    listDatas = new Gson().fromJson(jsonObject.getJSONArray("serviceInfos").toString(), new TypeToken<List<ServiceItemEntity>>() {}.getType());
                    //adapter
                    adapter = new ServiceAdapter(mContext,listDatas);
                    //bind
                    lv_service.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
            }
        });



    }





    //获取banner广告栏
    public void getBannerInfo() {

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("adArea","A1003");
        map.put("adSize","10");

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.AdInfoState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    bannersList = new Gson().fromJson(jsonObject.getJSONArray("adInfoList").toString(), new TypeToken<List<AdvertisementEntity>>() {}.getType());

                    //设置banner的指示器
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(4, 4, 4, 4);
                    ll_main3_banner.removeAllViews();
                    for (int i = 0; i < bannersList.size(); i++) {
                        ImageView imageView = new ImageView(mContext);
                        imageView.setLayoutParams(layoutParams);
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageResource(R.drawable.select_dot);
                        ll_main3_banner.addView(imageView);
                    }
                    bannerPagerAdapter = new Main3BannerPagerAdapter(mContext,bannersList);
                    vp_main3_banner.setAdapter(bannerPagerAdapter);
                    vp_main3_banner.setCurrentItem(bannersList.size()*1000);
                    currentItem = bannersList.size()*1000;

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }






    //用来完成图片切换的任务
    private class ViewPagerTask implements Runnable{

        public void run() {
            //实现我们的操作
            //改变当前页面
            currentItem = currentItem + 1;
            //Handler来实现图片切换
            handler.sendEmptyMessage(1);
        }
    }



    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentItem = position;

        //Banner的指示器
        for (int i = 0; i < bannersList.size() ; i++) {
            if (i == (currentItem) % bannersList.size()) {
                ll_main3_banner.getChildAt(i).setSelected(true);
            } else {
                ll_main3_banner.getChildAt(i).setSelected(false);
            }
        }


    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            //设定viewPager当前页面
                vp_main3_banner.setCurrentItem(currentItem);
        }
    };



}
